<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>游戏列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <!-- 搜索框 -->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getList">
              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true;">发布新游戏</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="gameList"
          border
          stripe
          @expand-change="expandSelect"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
        >
          <el-table-column type="index"></el-table-column>
          <el-table-column type="expand" label="游戏分支">
            <template>
              <el-row :gutter="20">
                <el-col :span="4">
                  <el-button type="primary" @click="addBranchDialogVisible = true;">添加新分支</el-button>
                </el-col>
              </el-row>
              <el-table
                :data="branchList"
                border
                stripe
              >
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="edition" label="分支名称">
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间">
                </el-table-column>
                <el-table-column label="是否发布">
                  <template slot-scope="scope">
                    {{ (scope.row.isReleased === 1) ? '是' : '否' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="300px">
                  <template slot-scope="scope">
                    <el-tooltip effect="dark" content="删除分支" placement="top" :enterable="false">
                      <el-button type="danger" icon="el-icon-delete" size="mini"
                                 @click="deleteBranch(scope.row.gameSourceId)"></el-button>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="添加分支资源" placement="top" :enterable="false">
                      <el-button type="primary" icon="el-icon-arrow-down" size="mini"
                                 @click="branchResourceDialogVisible = true;fillBranchInfo(scope.row.gameSourceId)"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="游戏名称">
          </el-table-column>
          <el-table-column label="已宣布">
            <template slot-scope="scope">
              {{ (scope.row.isAnnounced === 1) ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column
            label="已发布"
          >
            <template slot-scope="scope">
              {{ (scope.row.isReleased === 1) ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column
            label="价格"
            prop="price"
          >
          </el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="前往游戏页面" placement="top" :enterable="false">
                <el-button type="primary" icon="el-icon-arrow-right" size="mini"
                           @click="goToGamePage(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除游戏" placement="top" :enterable="false">
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="deleteGame(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="添加游戏资源" placement="top" :enterable="false">
                <el-button type="primary" icon="el-icon-arrow-down" size="mini"
                           @click="uploadDialogVisible = true;fillGameId(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="添加折扣" placement="top" :enterable="false">
                <el-button type="primary" icon="el-icon-arrow-down" size="mini"
                           @click="discountDialogVisible = true;fillDiscountForm(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <el-dialog
          title="创建新游戏"
          :visible.sync="addDialogVisible"
          width="80%">
          <el-form ref="addFormRef" :model="addForm" label-width="120px">
            <el-form-item prop="title" label="游戏名称">
              <el-input v-model="addForm.name" clearable></el-input>
            </el-form-item>
            <el-form-item prop="title" label="可见时间">
              <el-date-picker
                v-model="addForm.announceTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd hh:mm:ss">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="addForm.releaseTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd hh:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model="addForm.price" clearable></el-input>
            </el-form-item>
            <el-form-item prop="title" label="游戏类型">
              <el-select
                v-model="addForm.typeId"
                multiple
                filterable
                allow-create
                placeholder="请选择游戏类别">
                <el-option
                  v-for="item in gameTypeList"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <h2>游戏简介</h2>
          <mavon-editor v-model="addForm.profile" @imgAdd="$imgAdd"/>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addGame">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="创建新分支"
          :visible.sync="addBranchDialogVisible"
          width="80%">
          <el-form :model="addBranchForm" label-width="120px">
            <el-form-item label="分支名称">
              <el-input v-model="addBranchForm.edition" clearable></el-input>
            </el-form-item>
          </el-form>
          <h2>分支简介</h2>
          <mavon-editor v-model="addBranchForm.gameEditionProfile" @imgAdd="$imgAdd"/>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addBranchDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addBranch">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="添加游戏资源"
          :visible.sync="uploadDialogVisible"
          width="80%">
          <h2>上传游戏头像</h2>
          <el-upload
            action="123"
            :http-request="uploadGamePic"
            list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
          <h2>上传游戏媒体</h2>
          <el-upload
            action="123"
            class="upload-demo"
            drag
            :http-request="uploadGameMedia"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <span slot="footer" class="dialog-footer">
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="添加分支资源"
          :visible.sync="branchResourceDialogVisible"
          width="80%">
          <h2>上传分支资源</h2>
          <el-upload
            action="123"
            class="upload-demo"
            drag
            :http-request="uploadGameSource"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <span slot="footer" class="dialog-footer">
            <el-button @click="branchResourceDialogVisible = false">关 闭</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title=""
          :visible.sync="uploadDialogVisible"
          width="80%">
          <h2>上传游戏头像</h2>
          <el-upload
            action="123"
            :http-request="uploadGamePic"
            list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
          <h2>上传游戏媒体</h2>
          <el-upload
            action="123"
            class="upload-demo"
            drag
            :http-request="uploadGameMedia"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <span slot="footer" class="dialog-footer">
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="添加折扣"
          :visible.sync="discountDialogVisible"
          width="80%">
          <el-form :model="discountForm" label-width="120px">
            <el-form-item label="折后价格">
              <el-input v-model="discountForm.price" clearable></el-input>
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="discountForm.from_time"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd hh:mm:ss">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="discountForm.to_time"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd hh:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="discountDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setDiscount">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
        query: ''
      },
      total: 0,
      addDialogVisible: false,
      updateFormRules: {
        title: [
          {
            required: true,
            message: '请输入文档标题',
            trigger: 'blur'
          }
        ]
      },
      gameList: [],
      addForm: {
        isAnnounced: 0,
        isReleased: 0,
        name: '',
        price: 0,
        profile: '',
        announceTime: '',
        releaseTime: '',
        typeId: []
      },
      roleList: [],
      gameTypeList: [],
      uploadDialogVisible: false,
      uploadForm: {
        gameId: 0
      },
      discountDialogVisible: false,
      discountForm: {
        gameId: '',
        price: 0,
        from_time: '',
        to_time: ''
      },
      getRowKeys (row) {
        return row.id
      },
      expands: [],
      addBranchDialogVisible: false,
      branchList: [],
      addBranchForm: {
        gameId: 0,
        edition: '',
        isReleased: 1,
        gameEditionProfile: ''
      },
      branchInfo: {
        gameSourceId: 0
      },
      branchResourceDialogVisible: false
    }
  },
  created () {
    this.getList()
    this.getRoleList()
    this.getGameTypeList()
  },
  methods: {
    async getList () {
      const { data: res } = await this.$http.get('/api/developer/index', { params: this.queryInfo })
      if (res.code !== 200) {
        this.$message.error(res.message)
        return
      }
      console.log(res)
      this.gameList = res.data.games.records
      this.total = res.data.games.total
    },
    async getRoleList () {
      const { data: res } = await this.$http.get('/role/all')
      if (res.code === 200) {
        this.roleList = res.data.roles
      } else {
        this.$message.error('请求文档列表失败')
      }
    },
    addGame () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/api/developer/game/createGame', this.addForm)
        if (res.code === 200) {
          this.$message.success('添加文档成功')
          this.addDialogVisible = false
          await this.getList()
        } else {
          console.log(res)
          this.$message.error('添加游戏失败')
        }
      })
    },
    deleteGame (guidelineId) {
      this.$confirm('此操作将永久删除该游戏, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.get('/api/developer/game/deleteGame', { params: { gameId: guidelineId } })
        if (res.code === 200) {
          this.$message.success('删除游戏成功')
          await this.getList()
        } else {
          this.$message.error('删除游戏失败')
          console.log(res)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getList()
    },
    fillUpdateForm (info) {
      this.updateForm = info
    },
    $imgAdd (pos, $file) {
      const formData = new FormData()
      formData.append('file', $file)
      this.$http({
        url: '/api/document/upload/uploadGameSource',
        method: 'post',
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then((res) => {
        const _res = res.data.data
        this.$refs.md.$img2Url(pos, this.$http.defaults.baseURL + _res.url)
      })
    },
    goToGamePage (info) {
      console.log(info)
      window.location.href = 'https://www.baidu.com'
    },
    getRoleName (id) {
      for (const role of this.roleList) {
        if (role.id === id) {
          return role.roleName
        }
      }
    },
    getImgPath (path) {
      if (path !== null) {
        return this.$http.defaults.baseURL + path
      } else {
        return null
      }
    },
    async getGameTypeList () {
      const { data: res } = await this.$http.get('/api/gameType/selectGameType')
      if (res.code !== 200) {
        this.$message.error(res.message)
        return
      }
      console.log(res)
      this.gameTypeList = res.data
    },
    uploadGamePic (file) {
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('gameId', this.uploadForm.gameId)
      this.$http.post('/api/developer/uploadGameCover', formData).then(() => {
        this.$message.success('上传成功')
      })
    },
    uploadGameMedia (file) {
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('gameId', this.uploadForm.gameId)
      this.$http.post('/api/developer/uploadMedia', formData).then((res) => {
        console.log(res)
        this.$message.success('上传成功')
      })
    },
    uploadGameSource (file) {
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('gameSourceId', this.branchInfo.gameSourceId)
      console.log(this.branchInfo)
      this.$http.post('/api/developer/uploadGameSource', formData).then((res) => {
        console.log(res)
        this.$message.success('上传成功')
      })
    },
    fillGameId (id) {
      this.uploadForm.gameId = id
    },
    fillDiscountForm (info) {
      this.discountForm.gameId = info.id
      this.discountForm.price = info.price
    },
    expandSelect (row, expandedRows) {
      const _this = this
      _this.getBranchList(row.id)
      setTimeout(function () {
        _this.expands = []
        if (expandedRows.length > 0) {
          if (row) {
            _this.expands.push(row.id)
          }
        }
      }, 1000)
    },
    async getBranchList (info) {
      const { data: res } = await this.$http.get('/api/game/selectEdition', {
        params: {
          gameId: info,
          pageNum: 1,
          pageSize: 5
        }
      })
      if (res.code !== 200) {
        this.$message.error(res.message)
        return
      }
      console.log(res)
      this.branchList = res.data.records
      this.addBranchForm.gameId = info
    },
    async deleteBranch (gameSourceId) {
      this.$confirm('此操作将永久删除该分支, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.post('/api/developer/deleteGameSource', { gameSourceId: gameSourceId })
        if (res.code === 200) {
          this.$message.success('删除分支成功')
          await this.getList()
        } else {
          this.$message.error('删除分支失败')
          console.log(res)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    async addBranch () {
      console.log(this.addBranchForm)
      const { data: res } = await this.$http.post('/api/developer/createEdition', this.addBranchForm)
      if (res.code === 200) {
        this.$message.success('添加分支成功，正在刷新页面')
        this.addBranchDialogVisible = false
        location.reload()
      } else {
        console.log(res)
        this.$message.error('添加分支失败')
      }
    },
    fillBranchInfo (gameSourceId) {
      this.branchInfo.gameSourceId = gameSourceId
    },
    setDiscount () {
      this.$confirm('此操作将为该游戏打折, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(this.discountForm)
        const { data: res } = await this.$http.post('/api/developer/setDiscount', this.discountForm)
        if (res.code === 200) {
          this.$message.success('打折成功')
          this.discountDialogVisible = false
          await this.getList()
        } else {
          console.log(res)
          this.$message.error('打折失败')
        }
      }).catch(() => {
        this.$message.info('已取消')
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
